<template>
  <div class="pageBox pl20 pr20 pt10">
    <div class="score bg-ff">
      <span class="block fs30 f600">您对商品满意吗？</span>
      <div class="line mt20 mb30"></div>
      <div class="flexBox aiCenter">
        <span class="block fs26 mr15">总体</span>
        <van-rate v-model="scoreData.score" :size="23" color="#ffd21e" void-icon="star" void-color="#eee"
          :readonly="isView" />
        <span class="block fs26 ml15">{{ tipsTitle[scoreData.score] }}</span>
      </div>
      <div class="iptBox mt50">
        <van-cell-group inset>
          <van-field v-model="scoreData.comment" rows="6" autosize type="textarea" maxlength="200"
            placeholder="口味赞，分量足，包装好，推荐给大家" show-word-limit :disabled="isView" />
        </van-cell-group>
        <div class="flexBox flexBetween alignEnd pl25 pr25 pb15 mt15">
          <van-uploader v-model="fileList" accept="image/*" multiple max-count="3" :before-read="beforeUpload"
            :after-read="afterRead" :delete="handleDelete" :disabled="isView" :deletable="!isView" />
          <span v-if="fileList.length === 0" class="block fs22 c-666">上传图片，有机会成为优质评价哦</span>
        </div>
      </div>
      <div v-if="!isView" class="submitBtn">
        <van-button type="primary" block @click="submitScore">提交评价</van-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { commonUpload } from '@/api/common'
import { orderScore, orderScoreView } from '@/api/order'
import router from '@/router'
import { handleImgSrc } from '@/utils'
import { showToast } from 'vant'
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'

const fileList = ref<{ url: string, file: File }[]>([])
const scoreData = reactive({
  score: 0,
  comment: '',
  photo: [] as { url: string, file: File, path: string }[]
})
const route = useRoute()

const isView = computed(() => {
  return route.query.reviewed === '1'
})

const tipsTitle = {
  1: '非常不满意',
  2: '不满意',
  3: '一般',
  4: '满意',
  5: '非常满意'
}

const getScore = async () => {
  const { data } = await orderScoreView({ orderId: route.query.id })
  if (data.code === 0) {
    scoreData.score = data.data.score
    scoreData.comment = data.data.comment
    const temp = data.data.photo_url && data.data.photo_url.split(',').map(item => ({
      url: handleImgSrc(item),
      file: item,
      path: item
    })) || []
    scoreData.photo = temp
    fileList.value = temp
  }
}

const beforeUpload = async (file: File | File[]): Promise<File | File[]> => {
  const currentFile = Array.isArray(file) ? file[0] : file
  // if (fileList.value.length >= 3) {
  //   showToast('最多只能上传3张图片')
  //   throw new Error('最多只能上传3张图片')
  // }

  // 校验大小
  if (currentFile.size > 5 * 1024 * 1024) {
    showToast('文件大小不能超过 5MB')
    throw new Error('文件过大')
  }

  // 校验格式
  const validTypes = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif']
  if (!validTypes.includes(currentFile.type)) {
    showToast('仅支持 JPG/JPEG/PNG/GIF 格式')
    throw new Error('格式错误')
  }
  return Array.isArray(file) ? file : currentFile
}

const afterRead = async (file: { file: File }) => {
  const formData = new FormData()
  formData.append('file', file.file)
  formData.append('folder', 'score')

  const { data } = await commonUpload(formData)
  if (data.code === 0) {
    showToast('上传成功')
    const imgUrl = handleImgSrc(data.data.data)
    if (fileList.value.length < 3) {
      scoreData.photo.push({
        url: imgUrl,
        file: file.file,
        path: data.data.data
      })
    }
  } else {
    showToast(data.msg || '上传失败')
  }
}

const handleDelete = (index: number) => {
  if (isView.value) return false
  fileList.value.splice(index, 1)
  scoreData.photo.splice(index, 1)
}

const submitScore = async () => {
  if (!scoreData.score) return showToast('请选择评分')
  if (!scoreData.comment) return showToast('请输入评价')
  const params = {
    ...scoreData,
    order_id: route.query.id,
    photo_url: scoreData.photo?.map(item => item.path).join(',')
  }
  delete params.photo

  const { data } = await orderScore(params)
  if (data.code === 0) {
    showToast(`评价成功，已获得${data.data.balance}饭币`)
    setTimeout(() => {
      router.push('/order')
    }, 300)
  }
}

onMounted(() => {
  if (route.query.reviewed) getScore()
})
</script>

<style lang="scss" scoped>
.pageBox {
  background-color: #f7f7f7;
  height: 100%;

  .score {
    border-radius: 35px;
    height: 100%;
    padding: 20px;
    position: relative;

    .iptBox {
      border-radius: 15px;
      background: #eeeeee;

      .van-field {
        background: #eeeeee;
        padding-left: 0;
        padding-right: 0;
      }
    }

    .submitBtn {
      position: absolute;
      bottom: 20px;
      left: 20px;
      right: 20px;
      width: 95%;

      .van-button--primary {
        background: #40a9ff;
        border-color: #40a9ff;
      }
    }
  }

  .line {
    width: 100%;
    height: 1px;
    background: #000000;
    opacity: 0.05;
  }
}
</style>
